<template>
  <div class="role-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button :icon="Plus" type="primary" @click="handleEdit($event)">
          添加
        </el-button>
        <el-button :icon="Delete" type="danger" @click="handleDelete($event)">
          批量删除
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form inline :model="queryForm" @submit.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.keywords"
              clearable
              placeholder="请输入角色"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="multipleTableRef"
      v-loading="listLoading"
      border
      :data="list"
      :row-class-name="rowClass"
      height="60vh"
      @row-click="toggleSelection"
      @selection-change="setSelectRows"
    >
      <el-table-column align="center" show-overflow-tooltip type="selection" />
      <el-table-column align="center" label="序号" width="55">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="ID"
        prop="id"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="角色码"
        prop="code"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="角色名称"
        prop="name"
        show-overflow-tooltip
      />
      <el-table-column label="状态" align="center" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.status === 1 ? '启用' : '禁用' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        align="center"
        label="操作"
        show-overflow-tooltip
        width="300"
      >
        <template #default="{ row }">
          <el-button
            text
            type="primary"
            @click="handleAllocation(row, 'allocation')"
          >
            分配权限
          </el-button>
          <el-button text type="primary" @click="handleEdit(row, 'edit')">
            编辑
          </el-button>
          <el-button text type="primary" @click="handleDelete(row)">
            删除
          </el-button>
          <!--          <el-tooltip-->
          <!--            class="box-item"-->
          <!--            effect="dark"-->
          <!--            content="编辑"-->
          <!--            placement="top"-->
          <!--          >-->
          <!--            <el-button-->
          <!--              :icon="Edit"-->
          <!--              type="warning"-->
          <!--              @click="handleEdit(row, 'edit')"-->
          <!--            />-->
          <!--          </el-tooltip>-->
          <!--          <el-tooltip-->
          <!--            class="box-item"-->
          <!--            effect="dark"-->
          <!--            content="删除"-->
          <!--            placement="top"-->
          <!--          >-->
          <!--            <el-button-->
          <!--              :icon="Delete"-->
          <!--              type="danger"-->
          <!--              @click="handleDelete(row)"-->
          <!--            />-->
          <!--          </el-tooltip>-->
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="editRef" @fetch-data="fetchData" />
    <allot ref="allotRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import {
    doDelete,
    fetchRoleroleMenuIds,
    getList,
    fetchRoleDetail,
  } from '@/api/roleManagement'
  import { fetchMenusList } from '@/api/menuManagement'
  import { Delete, Plus, Search, Edit } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'RoleManagement',
    components: {
      Edit: defineAsyncComponent(() =>
        import('./components/RoleManagementEdit')
      ),
      Allot: defineAsyncComponent(() =>
        import('./components/AssignRoleRoutingButtonPermissions')
      ),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        editRef: null,
        allotRef: null,
        multipleTableRef: null,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        selectRow: [],
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          keywords: '',
        },
        MenusList: [],
      })

      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const handleAllocation = async (row) => {
        if (row.id) {
          try {
            state.listLoading = true
            const { data: data } = await fetchRoleroleMenuIds({
              roleId: row.id,
            })
            state['allotRef'].showEdit(row, state.MenusList, data)
            state.listLoading = false
          } catch (e) {
            console.error(e)
          }
        } else {
          // state['allotRef'].showEdit('', state.MenusList)
        }
      }
      const handleEdit = async (row) => {
        if (row.id) {
          try {
            state.listLoading = true
            const { data: data } = await fetchRoleDetail({
              roleId: row.id,
            })
            state['editRef'].showEdit(data)
            state.listLoading = false
          } catch (e) {
            console.error(e)
          }
        } else {
          state['editRef'].showEdit()
        }
      }
      watch(
        () => state.selectRows,
        (val) => {
          // console.log(`新的值是：${newValue}，旧的值是：${oldValue}`)
          state.selectRow = []
          if (val.length > 0) {
            console.log(val, state.selectRows, 1122)
            state.selectRows.forEach((item) => {
              state.selectRow.push(state.list.indexOf(item))
            })
          }
        },
        {
          deep: true,
        }
      )
      //勾选数据行的 Checkbox 时触发的事件
      const rowClass = ({ row, rowIndex }) => {
        if (state.selectRow.includes(rowIndex)) {
          console.log(row)
          return 'slecleRowColor'
        }
      }
      //点击行
      const toggleSelection = (rows) => {
        if (rows) {
          state.multipleTableRef &&
            state.multipleTableRef.toggleRowSelection(rows, undefined)
        } else {
          // console.log(555,state.selectRows)
          state.multipleTableRef.clearSelection()
        }
      }
      const handleDelete = (row) => {
        if (row.id) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            try {
              const { msg } = await doDelete({ ids: row.id })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            } catch (err) {
              console.error(err)
            }
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.map((item) => item.id).join()
            $baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNum = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNum = 1
        fetchData()
      }
      const fetchData = async () => {
        try {
          state.listLoading = true
          const {
            data: { list, total },
          } = await getList(state.queryForm)
          state.list = list
          state.total = total
          state.listLoading = false
        } catch (e) {
          console.error(e)
        }
      }

      const fetchMenusListFunc = async () => {
        try {
          state.listLoading = true
          const { data: data } = await fetchMenusList()
          state.MenusList = data
          state.listLoading = false
        } catch (e) {
          console.error(e)
        }
      }

      onMounted(() => {
        fetchData()
        fetchMenusListFunc()
      })

      return {
        ...toRefs(state),
        setSelectRows,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        handleAllocation,
        Delete,
        Plus,
        Search,
        Edit,
        rowClass,
        toggleSelection,
      }
    },
  })
</script>

<style scoped>
  :deep() .el-table .slecleRowColor {
    background: #eaf4ff !important;
  }

  :deep() .el-table tbody tr:hover > td {
    background-color: #eaf4ff !important;
  }
</style>
